﻿namespace Pibby.Core.Playlist
{
    using System;
    using System.IO;

    using Pibby.Core.IO;
    using invrt;

	public static class WindowsPlaylistWriter
	{
		public static void SaveTo(IFolder folder, string playlistName, IPlaylist playlist)
		{
			if (folder == null)
				throw new ArgumentNullException("folder", "Folder cannot be null");

			if (string.IsNullOrEmpty(playlistName))
				throw new ArgumentNullException("playlistName", "Play list name cannot be blank");

			if (playlist == null)
				throw new ArgumentNullException("playlist", "Playlist cannot be null");

			var factory = InversionOfController.Factory.CreateTypeOf<ITextWriterFactory>();

			using (var writer = factory.FromFile(folder.PathToFile(playlistName)))
			{
				WindowsPlaylistWriter.SaveTo(writer, playlist, folder);
			}
		}

		public static void SaveTo(TextWriter writer, IPlaylist playlist, IFolder baseFolder)
		{
			if (writer == null)
				throw new ArgumentNullException("writer", Resources.Playlist_NullObjectError);

			if (playlist == null)
				throw new ArgumentNullException("playlist", Resources.Playlist_NullObjectError);

			writer.WriteLine("<?wpl version=\"1.0\"?>");
			writer.WriteLine("<smil>");

			writer.WriteLine("\t<head>");
			writer.WriteLine("\t\t<meta name=\"Generator\" content=\"Pibby\"/>");
			writer.WriteLine("\t\t<meta name=\"ItemCount\" content=\"{0}\"/>", playlist.Items.Count);
			writer.WriteLine("\t</head>");

			writer.WriteLine("\t<body>");
			writer.WriteLine("\t\t<seq>");

			foreach (PlaylistItem item in playlist.Items)
			{
				writer.WriteLine("\t\t\t<media src=\"{0}\" />", item.RelativePathTo(baseFolder.Path));
			}

			writer.WriteLine("\t\t</seq>");
			writer.WriteLine("\t</body>");

			writer.WriteLine("</smil>");
		}
	}
}
